﻿
/* Config validation */
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null,
    decorateElement: true,
    errorClass: "error",
    errorMessageClass: "error-desc"
});

var mustEqual = function (val, other) {
    return val == other();
};
var focusWorkPhone1 = false;
var agentViewModel = new function () {
    this.FirstName = ko.observable(data.FirstName)
		.extend({ maxLength: 20 })
		.extend({ required: { message: GetRequiredFormat("First Name")} })
		.extend({ pattern: { message: GetInvalidFormat('First Name'), params: PARAM_NAME} });

    this.LastName = ko.observable(data.LastName)
		.extend({ maxLength: 30 })
		.extend({ required: { message: GetRequiredFormat("Last Name")} })
		.extend({ pattern: { message: GetInvalidFormat('Last Name'), params: PARAM_NAME} });

    this.Email = ko.observable(data.Email)
		.extend({ maxLength: 100 })
		.extend({ required: { message: GetRequiredFormat("Email")} })
		.extend({ pattern: { message: GetInvalidFormat('email'), params: PARAM_EMAIL} });
    this.WorkPhoneExt = ko.observable(data.WorkPhoneExt);
    if (this.WorkPhoneExt() == '') {
        this.WorkPhoneExt('Ext');
    }
    this.NewPassword = ko.observable("")
		.extend({ minLength: 6, maxLength: 20 })
        .extend({ pattern: { message: 'Password must follow stated requirements.', params: '^(?=.{6})(?=.*[a-zA-Z]{1})(?=.*[0-9]{1}).*$'} });
    this.ConfirmPassword = ko.observable("")
        .extend({ pattern: { message: 'Password must follow stated requirements.', params: '^(?=.{6})(?=.*[a-zA-Z]{1})(?=.*[0-9]{1}).*$'} });
    this.CellPhone1 = ko.observable(data.WorkPhone.substring(0, 3) + "");
    this.CellPhone2 = ko.observable(data.WorkPhone.substring(3, 6) + "");
    this.CellPhone3 = ko.observable(data.WorkPhone.substring(6, 10) + "");

    this.WorkPhone = ko.computed(function () {
        return this.CellPhone1() + this.CellPhone2() + this.CellPhone3();
    }, this).extend({
        minLength: { params: 10, message: "Enter a valid phone number" },
        maxLength: { params: 10, message: "Enter a valid phone number" },
        required: { message: "Phone number is required" }
    }).extend({
        phoneUS: { message: "Enter a valid phone number" }
    });
    this.msgError = ko.observable("");

    this.visibleErrormsg = ko.observable(false);
    this.visiblemsg = ko.observable(false);
    // Each input
    $(":input").focus(function () {
        var id = $(this).attr("id");

        // group 1
        if (id == "cell1" || id == "cell2" || id == "cell3") {
            $("#cell1").parent('.input-holder-setup').find('.error-desc').remove();
            var message = $(this).parents(".groupinput").find('.error-desc');
            // group message
            if (focusWorkPhone1) {
                message.show();
            }
            else {
                message.hide();
            }
        }

        if (id == "WorkPhoneExt") {
            if ($("#WorkPhoneExt").val() == "Ext") {
                $("#WorkPhoneExt").val("");
            }
        }
    });

    $(":input").focusout(function () {
        var id = $(this).attr("id");

        var phone = $('#WorkPhone').val();
        if (id == "cell1" || id == "cell2" || id == "cell3") {
            $("#cell1").parent('.input-holder-setup').find('.error-desc').remove();
            var message = $(this).parents(".groupinput").find('.error-desc');
            //group message
            if (phone.length == 10 && message.text() == '') {
                message.hide();
                focusWorkPhone1 = true;
            }
            else {
                message.show();
                focusWorkPhone1 = false;
            }
        }

        if (id == "WorkPhoneExt") {
            if (($("#WorkPhoneExt").val() == null) || ($("#WorkPhoneExt").val() == '')) {
                $("#WorkPhoneExt").val("Ext");
            }
        }
    });

    // Submit function
    this.EditUser = function () {
        // If current password is null or empty
        // Submit form without update/ change password
        this.visibleErrormsg(false);
        this.visiblemsg(false);
        if (agentViewModel.errors().length == 0) {
            var _agentid = data.AgentId;
            var _firstname = this.FirstName();
            var _lastname = this.LastName();
            var _email = this.Email();
            var _workphone = this.WorkPhone();
            var _workphoneext = this.WorkPhoneExt();
            var _newpassword = this.NewPassword();
            var dataPost = { "agentid": _agentid, "firstname": _firstname, "lastname": _lastname, "email": _email, "workphone": _workphone, "workphoneext": _workphoneext, "newpassword": _newpassword };
            $.ajax({
                type: "POST",
                url: "/User/EditUser",
                data: dataPost,
                dataType: "json",
                success: function (model, textStatus, jqXHR) {
                    if (model == "") {
                        agentViewModel.msgError("Update successful.");
                        agentViewModel.visiblemsg(true);
                    }
                    else {
                        //log error
                        agentViewModel.msgError(model);
                        agentViewModel.visibleErrormsg(true);
                    }
                },
                error: function (xhr, status, error) {
                    showPopupError();
                }
            });
        }
        this.errors.showAllMessages();
        return false;
    };
};
agentViewModel.ConfirmPassword = ko.observable("").extend({
    validation: { validator: mustEqual, message: 'The two passwords entered do not match.', params: agentViewModel.NewPassword }
}),
agentViewModel.errors = ko.validation.group(agentViewModel);
ko.validation.rules.pattern.message = 'Invalid.';
ko.applyBindings(agentViewModel, document.getElementById("agent"));